﻿using ERPPublic;
using MediatR;
using Newtonsoft.Json;
using WarehouseManagement.Application.Command.WarehouseSAppCommand;
using WarehouseManagement.Domain.DTO;
using WarehouseManagement.Infrstructre.Interface;

namespace WarehouseManagement.Application.CommandHandler.WarehouseSAppCommandHandler
{
    /// <summary>
    /// 入库申请删除中介者
    /// </summary>
    public class WarehouseSAppDelCommandHandler:IRequestHandler<WarehouseSAppDelCommand,int>
    {
        private readonly lnterfaceWarehouseSAppRepository _warehouseSAppRepository;//仓库入库申请表

        public WarehouseSAppDelCommandHandler(lnterfaceWarehouseSAppRepository warehouseSAppRepository)
        {
            _warehouseSAppRepository = warehouseSAppRepository;
        }

        public async Task<int> Handle(WarehouseSAppDelCommand request, CancellationToken cancellationToken)
        {
            var count = 0;
            foreach (var id in request.id)
            {
                var res = (await _warehouseSAppRepository.GetAll()).First(x=>x.ShippRequestAppId==id);
                //删除仓库入库申请表
                if (res != null)
                {
                    res.IsDel = true;
                    res.DelName = request.DelName;
                    res.DelTime = DateTime.Now;
                    await _warehouseSAppRepository.UpdateAsync(res);
                    MessageCreateDto dto = new MessageCreateDto();
                    dto.MType = "入库申请";
                    dto.Title = "入库申请删除";
                    dto.SendTime = DateTime.Now;
                    await MessageCreates(dto);
                    count = 1;
                }
                else
                {
                    count = -1;//不存在
                }
            }
            return count;
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="dtos"></param>
        /// <returns></returns>
        public async Task<int> MessageCreates(MessageCreateDto dtos)
        {
            string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI1MCIsInNpZCI6IjE4NjcwOTU3MzQ0NjIwNTg0OTYiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL2dyb3Vwc2lkIjoiMTksMTkiLCJqdGkiOiI1MGYyMWRmZS0yNWQ3LTQ1OTQtOTg1Yi0wZTM2MDhhZjJiNmYiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoi5LuY5rSb5ZiJIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvdXJpIjoiLyIsImlzcyI6IlJlbmFvYm8yMDA0IiwiYXVkIjoiV2VpZnV3dTIyMDNBIn0._wh23n1M7asMGST9NyeZj-5rk5ICAiOFv6yDk6e2o7Y";
            HttpClientWrapper cilent = new HttpClientWrapper(token);
            string chanpin = "http://116.205.121.197:8000/erpcp/api/Message/SendMessage";
            string jsonstr = JsonConvert.SerializeObject(dtos);
            string postReponse = await cilent.PostAsync(chanpin, jsonstr);
            return 1;
        }
    }
}
